package cn.sx10.controller;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

@WebServlet("/loginfo.do")
public class userController extends HttpServlet {
    @Override
    protected  void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String choick= request.getParameter("choick");
        switch (choick){
            case "login":
                login(request,response);
            break;
            case "verify":
                verify(request,response);
                break;
        }
    }

    private void verify(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        System.out.println("已进入");
        int num = (int) (Math.random()*(10000 - 1000 +1)+1000);
        request.getSession().setAttribute("num",num);
        String jsonString ="{\"result\":\""+num+"\"}" ;
        PrintWriter writer = response.getWriter();
        writer.print(jsonString);
        //关闭数据写操作
        writer.flush();
        writer.close();
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userName = request.getParameter("userName");
        String Pwd = request.getParameter("password");
        int userVerify = Integer.parseInt(request.getParameter("verify"));
        int verify = (int) request.getSession().getAttribute("num");

        System.out.println(userVerify);
        System.out.println(verify);

        String id ="admin";
        String pwd ="123";

        if (userVerify==verify){
            if (userName.equals(id) ){
                request.getSession().setAttribute("userName",userName);
                response.sendRedirect("student.do?action=list");
            }
        }
        else {
            response.sendRedirect("login.jsp");
        }
    }
}
